<?php


namespace App\library\services;


use App\Models\Building;
use App\Models\BuildingMongo;
use App\Models\Cities;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use QL\QueryList;

class BuildingService extends BaseServices
{
    /**
     * Author:YangXinPeng
     * 热门楼盘
     * @param $province
     * @return array
     */
    public static function getHotBuilding($province)
    {
        if (isset($province)) {
            $data = Building::where('province', $province)
                ->orderBy('visit', 'desc')
                ->take(5)
                ->get();
            $data && $data = $data->toArray();
            return self::success('成功', $data);
        } else {
            return self::fail('参数错误');
        }
    }

    /**
     * Author:YangXinPeng
     * 楼盘列表
     * @param $province
     * @return array|mixed
     */
    public static function getBuilding($province)
    {
//        Redis::select(12);
//        if (isset($province)) {
//            $key = config("setting.buildingKey") . $province;
//            if (Redis::exists($key)) {
//                $json = Redis::get($key);
//                return self::success('成功', json_decode($json, true));
//            } else {
//                $data = Building::where('province', $province)->get();
//                $data && $data = $data->toArray();
//                Redis::set($key, json_encode($data));
//                return self::success('成功', $data);
//            }
//        } else {
//            return self::fail('参数错误');
//        }

        //mongo
      $data = BuildingMongo::select($province);
      return self::success('成功', $data);
    }


    public static function getBuildingById($id)
    {
        if (!is_numeric($id)) {
            return self::fail('参数错误');
        }
        $building = Building::find($id);
        $building && $building = $building->toArray();
        return self::success('成功', $building);
    }


    /**
     * Author:YangXinPeng
     * 楼盘信息爬虫获取
     * @return mixed
     */
    public function catchResource()
    {
        $url = 'https://bj.fang.ke.com/loupan';
        // 定义采集规则
        $rules = [
            // 采集房源标题
            'title' => ['.resblock-name a', 'title'],
            // 采集房源标签
            'tags' => ['.resblock-name span:eq(1)', 'text'],
            // 采集房源详细地址
            'address' => ['.resblock-location', 'text'],
            // 采集房源户型
            'type' => ['.resblock-room span:not(.area)', 'text'],
            // 采集房源户型面积
            'area' => ['.resblock-room .area', 'text'],
            // 采集房源每平方米价格
            'avg_price' => ['.resblock-price .main-price .number', 'text'],
            // 采集房源每总价
            'total_price' => ['.resblock-price .second', 'text'],
            // 采集房源效果图
            'image' => ['.resblock-img-wrapper img ', 'data-original'],
        ];
        $range = '.resblock-list-wrapper .resblock-list';
        $data = QueryList::Query($url, $rules, $range)->getData(function ($item) {
            $item['type'] = $this->findNum($item['type']);
            $item['area'] = $this->findArea($item['area']);
            $item['total_price'] = $this->findPrice($item['total_price']);
            return $item;
        });
        foreach ($data as $value) {
            $arr = explode("/", $value['address']);
            $res = $this->findId($arr);
            $value = array_merge($value, $res);
            $flag = \App\Models\Building::create($value);
        }
        return $flag;
    }


    /**
     * Author:YangXinPeng
     * 字符串中寻找所含的数字
     * @param $str
     * @return string
     */
    public function findNum($str)
    {
        $str = trim($str);
        if (empty($str)) {
            return '';
        }
        $result = '';
        for ($i = 0; $i < strlen($str); $i++) {
            if (is_numeric($str[$i])) {
                $result .= $str[$i] . ",";
            }
        }
        return rtrim($result, ",");
    }

    /**
     * Author:YangXinPeng
     * 返回建筑面积
     * @param $str
     * @return false|string
     */
    public function findArea($str)
    {
        $str = trim($str);
        if (empty($str)) {
            return '';
        }
        $result = substr($str, strpos($str, ' '), -3);
        return $result;
    }

    /**
     * Author:YangXinPeng
     * 返回价格
     * @param $str
     * @return false|string
     */
    public function findPrice($str)
    {
        $str = trim($str);
        if (empty($str)) {
            return '';
        }
        $result = substr($str, 6, -9);
        return $result;
    }

    /**
     * Author:YangXinPeng
     * 返回城市ID
     * @param $arr
     * @return array
     */
    public function findId($arr)
    {
        $region = $arr[0] . "区";
        $data = Cities::all()->toArray();
        $res = [];
        foreach ($data as $value) {
            if ($value['name'] == $region) {
                $res['region'] = $value['id'];
                $res['city'] = $value['pid'];
                $res['province'] = $value['pid'];
            }
        }
        return $res;
    }

}
